import _Vue from 'vue';
import axios, { AxiosInstance, AxiosResponse, AxiosRequestConfig } from 'axios';
import { CryptUtil } from '@/utils/CryptUtil';
// import { MAINHOST, QAHOST, commonParams } from '@/config';
// import { getToken } from '@/utils/common';
// import qs from 'qs';
import router from '@/router'

class AxiosHttpRequest {
  private axios: any;
  private dischargedApi: Array<string> = [
    '/system/api/searchHumanName',
    '/system/api/login',
    '/system/api/template',
    '/system/api/info/sysconfig/item',
    '/system/api/unitinfo/loadaddress'
  ]

  constructor(ax: any) {
    this.axios = ax;
    // axios 配置
    this.axios.defaults.timeout = 120 * 1000;
    // this.axios.defaults.baseURL = process.env.NODE_ENV === 'production' ? MAINHOST : QAHOST;
    // @ts-ignore
    this.axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';
    // this.axios.defaults.baseURL = 'http://119.3.251.200:8097';

    // http request 拦截器
    this.axios.interceptors.request.use(
      (config: any) => {
        // 在此处添加请求头等，如添加token
        if (sessionStorage.getItem('token')) {
          config.headers['Authorization'] = sessionStorage.getItem('token');
          config.headers['Verify'] = CryptUtil.desEncrypt(new Date().getTime() + '');
        } else {
          if (this.dischargedApi.includes(config.url)) {
            config.headers['Authorization'] = 'eyJhbGciOiJIUzUxMiJ9.eyJISSI6LTEsIlVJIjoxLCJITiI6IumZtuaYjum-mSIsIlJJIjoiIiwiVU4iOiLlub_opb_lo67ml4_oh6rmsrvljLoiLCJVQyI6Ii8xLyJ9.DAWCZpyQSAngIv4NBIxxz19mrLGvHdZI8WdNim5wlI0yZoa0WkHCrb-tyDY4v1MpbpEl4TWEOndnZmxxdma0YQ';
            config.headers['Verify'] = CryptUtil.desEncrypt(new Date().getTime() + '');
          }
        }

        let sysConfigMapString = sessionStorage.getItem('sysConfigMap') as string;
        debugger
        let sysConfigMap = JSON.parse(sysConfigMapString);
        if (sysConfigMap) {
          let WEB_API_ENCRYPT_LIST = JSON.parse(sessionStorage.getItem('sysConfigMap') as string).WEB_API_ENCRYPT_LIST || [];
          if (WEB_API_ENCRYPT_LIST.length > 0) {
            WEB_API_ENCRYPT_LIST = WEB_API_ENCRYPT_LIST.split(';');
            for (let i = 0; i < WEB_API_ENCRYPT_LIST.length; i++) {
              if (config.url.indexOf(WEB_API_ENCRYPT_LIST[i]) > -1) {
                config.headers['encry'] = 'true';
                config.data = { data: CryptUtil.desEncrypt(JSON.stringify(config.data)) }
                break;
              }
            }

          }
        }
        return config;
      },
      (error: any) => {
        return Promise.reject(error);
      }
    );

    // http response 拦截器
    this.axios.interceptors.response.use(
      (response: any) => {
        if (response.headers['encry'] === 'true') {
          response.data['data'] = JSON.parse(CryptUtil.desDecrypt(response.data.data));
        }
        return response;
      },
      (error: any) => {
        if (error && error.response) {
          switch (error.response.status) {
            case 400: error.message = '请求错误(400)'; break;
            case 401: error.message = '未授权,请重新登录(401)'; break;
            case 403: error.message = '拒绝访问(403)'; break;
            case 404: error.message = `请求地址错误: ${error.response.config.url}`; break;
            case 405: error.message = '请求方法未允许(405)'; break;
            case 408: error.message = '请求超时(408)'; break;
            case 500: error.message = '服务端内部错误(500)'; break;
            case 501: error.message = '服务未实现(501)'; break;
            case 502: error.message = '网络错误(502)'; break;
            case 503: error.message = '服务不可用(503)'; break;
            case 504: error.message = '网络超时(504)'; break;
            case 505: error.message = 'HTTP版本不受支持(505)'; break;
            default: error.message = `连接错误: ${error.message}`;
          }
        } else if (error.message.includes('timeout')) {
          error.message = '请求超时';
        } else {
          // error.message = '连接服务器失败，请联系管理员';
        }
        if (error && error.response && (error.response.status === 401 || error.response.status === 403)) {
          _Vue.prototype.$message.warning({
            content: "token失效，请重新登录",
            duration: 3,
            onClose: () => {
              // 清除token
              sessionStorage.clear();
              // window.close();
              router.push({ name: 'Login' });
            }
          });
        } else {
          _Vue.prototype.$message.error(
            error.message
          );
        }
        return Promise.reject(error.response);
      }
    );
  }

  public get(url: string, params: object, config: object) {
    //增加时间戳 防止缓存
    params = {
      _t: new Date().getTime(),
      ...params
    }
    return this.axios({
      method: 'get',
      url,
      params,
      ...config,
    }).then(
      (res: any) => {
        if (res && res.data) {
          if (!res.data.ok) {
            _Vue.prototype.$message.error(
              res.data.message ? res.data.message : ""
            );
            return;
          }
          return res.data.data || res.data.dataMap;
        }
      }
    );
  }

  // 获取静态资源
  public getStatic(url: string, params: object, config: object) {
    //增加时间戳 防止缓存
    params = {
      _t: new Date().getTime(),
      ...params
    }
    return this.axios({
      method: 'get',
      url,
      params,
      ...config,
    }).then(
      (res: any) => {
        if (res && res.data) {
          return res.data;
        } else {
          _Vue.prototype.$message.error('资源获取失败!');
        }
      }
    );
  }

  public getTrace(url: string, params: object, config: object) {
    //增加时间戳 防止缓存
    params = {
      _t: new Date().getTime(),
      ...params
    }
    return this.axios({
      method: 'get',
      url,
      params,
      ...config,
    }).then(
      (res: any) => {
        if (res && res.data) {
          return res.data.data || res.data.dataMap;
        }
      }
    );
  }

  public post(url: string, params: object) {
    return this.axios({
      method: 'post',
      url,
      // data: qs.stringify(params),
      data: params,
    }).then(
      (res: any) => {
        debugger
        if (res && res.data) {
          if (!res.data.ok) {
            _Vue.prototype.$message.error(
              `${res.data.message ? `${res.data.message}` : "post"}`,
            );
            return;
          }
          return res.data.data || res.data.dataMap;
        }
      }
    );
  }

  public postJson(url: string, params: object) {
    return this.axios({
      method: 'post',
      url,
      data: JSON.stringify(params),
      headers: { "Content-Type": "application/json;charset=utf-8" },
    }).then(
      (res: any) => {
        if (res && res.data) {
          if ((res.data.hasOwnProperty("success") && !res.data.success) || (res.data.hasOwnProperty("hasError") && res.data.hasError)) {
            _Vue.prototype.$Notice.error({
              title: "请求失败",
              desc: res.data.message ? res.data.message : ""
            });
            return;
          }
          return res.data.data || res.data.dataMap;
        }
      }
    );
  }

  public uploadFile(url: string, data: FormData, config1?: object) {
    let config = {
      // 请求头信息
      headers: { 'Content-Type': 'multipart/form-data' },
      ...config1
    };
    return this.axios.post(url, data, config).then(
      (res: any) => {
        if (res && res.data) {
          if (!res.data.ok) {
            _Vue.prototype.$Notice.error({
              title: "请求失败",
              desc: res.data.message ? res.data.message : ""
            });
            return;
          }
          return res.data.data || res.data.dataMap;
        }
      }
    );
  }

  public getData(url: string, params: object) {
    return this.axios({
      method: 'get',
      url,
      params: params,
      responseType: 'blob'
    }).then((res:any) => {
      let url = window.URL.createObjectURL(new Blob([res.data]));
      let link = document.createElement('a');
      link.style.display = 'none';
      link.href = url;
      // @ts-ignore
      link.setAttribute('download', params['fileName']);
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    });
  }

  public postData(url: string, fileName: string, params: object) {
    return this.axios({
      method: 'post',
      url,
      data: params,
      responseType: 'blob'
    }).then((res: any) => {
      let url = window.URL.createObjectURL(new Blob([res.data]));
      let link = document.createElement('a');
      link.style.display = 'none';
      link.href = url;
      // @ts-ignore
      link.setAttribute('download', fileName);
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    });
  }
}

const $axios: AxiosHttpRequest = new AxiosHttpRequest(axios);
export function AxiosRequest(Vue: typeof _Vue): void {
  Vue.prototype.$axios = $axios;
}
